<?php

require_once ROOT_DIR.'models/Todo.php';
require_once ROOT_DIR.'views/TodoJSON.php';
require_once ROOT_DIR.'controls/RightHelper.php';

/**
 * Retrieves a the list of todos matching the parameters and echos the resulting view.
 * 
 * @param int $userID
 * @param int $listID
 * @param int $from Default is 0
 * @param int $rows Default is 30
 * @param string $sort Default is 'cD'. Possible values are 'cD', 'tD', 's', 'pH'
 * @param boolean $includingPast Default is trues
 */
function getTodos($userID, $listID, $from = 0, $rows = 30, $sort = 'cD', $order = 'desc', $includingPast = true, $linkedLists = false){
	
	if(is_null($userID) && is_null($listID)) $userID = $_SESSION['USER_ID'];
	if(is_null($from)) $from = 0;
	if(is_null($rows)) $rows = 30;
	if(is_null($sort)) $sort = 'cD';
	if(is_null($order)) $order = 'desc';
	if(is_null($includingPast)) $includingPast = true;
	if(is_null($linkedLists)) $linkedLists = false;
	if(!is_null($listID)){
		$list = TodoList::getList($listID);
	} else {
		$list = false;
	}
	
	if(!is_null($list)){
		if($_SESSION['USER_NAME'] == 'admin' || (!is_null($userID) && $userID == $_SESSION['USER_ID']) || ($list && ($list->getOwnerID() == $_SESSION['USER_ID'] || RightHelper::sharesList($list)))){
			$todos = Todo::getTodos($userID, $listID, $from, $rows, $sort, $order, $includingPast);
			$count = Todo::getTodoCount($listID, $userID, null, $includingPast);
			echo TodoJSON::getView($todos, $count, $linkedLists);
		} else {
			$res = new ResultJSON(true, session_id(), ERROR_NOT_ALLOWED);
			echo $res->renderView();
		}
	} else {
		$res = new ResultJSON(true, session_id(), ERROR_LIST_DOES_NOT_EXIST);
		echo $res->renderView();
	}
}

?>